﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Threading;
using System.Data.SqlClient;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.ComponentModel;
using System.Data;

namespace ReadWriteini
{
    class ReadWriteIni
    {
        #region  字段声明
        private string _Key1;
        public string Key1
        {
            get { return _Key1; }
            set { _Key1 = value; }
        }
        private string _Key2;
        public string Key2
        {
            get { return _Key2; }
            set { _Key2 = value; }
        }

        private string _ServerName;
        public string ServerName
        {
            get { return _ServerName; }
            set { _ServerName = value; }
        }

        string _DataBaseName = null;
        public string DataBaseName
        {
            get { return _DataBaseName; }
            set { _DataBaseName = value; }
        }

        string _UidName;
        public string UidName
        {
            get { return _UidName; }
            set { _UidName = value; }
        }

        string _PassWordName;
        public string PassWordName
        {
            get { return _PassWordName; }
            set { _PassWordName = value; }
        }
        string _ConnetStr;
        public string ConnetStr
        {
            get { return _ConnetStr; }
            set { _ConnetStr = value; }
        }
        string _IntPath;
        public string IntPath
        {
            get { return _IntPath; }
            set { _IntPath = value; }
        }

        string _RecordUrl;
        public string RecordUrl
        {
            get { return _RecordUrl; }
            set { _RecordUrl = value; }
        }

        string _SchoolName;
        public string SchoolName
        {
            get { return _SchoolName; }
            set { _SchoolName = value; }
        }

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(
            string lpAppName,
            string lpKeyName,
            string lpDefault,
            StringBuilder lpReturnedString,
            int nSize,
            string lpFileName);
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(
            string mpAppName,
            string mpKeyName,
            string mpDefault,
            string mpFileName);
        #endregion

        public ReadWriteIni()
        {
            Key1 = "yunyudig"; //加密密匙1
            Key2 = "dongwend"; //加密密匙2
            IntPath = System.Environment.CurrentDirectory + "\\ConnectString.ini";//INI文件的物理地址
        }

        public string ContentReader(string area, string key, string def)
        {
            StringBuilder stringBuilder = new StringBuilder(1024); 				//定义一个最大长度为1024的可变字符串
            GetPrivateProfileString(area, key, def, stringBuilder, 1024, IntPath); 			//读取INI文件
            return stringBuilder.ToString();								//返回INI文件的内容
        }

        //加密
        /// <summary>
        ///Des加密函数
        /// </summary>
        /// <param name="sourceString">加密字符</param>
        /// <param name="key">加密钥匙1</param>
        /// <param name="iv">加密钥匙2</param>
        /// <returns></returns>
        public string EncryptDES(string sourceString, string key, string iv)
        {
            try
            {
                byte[] btKey = Encoding.UTF8.GetBytes(key);

                byte[] btIV = Encoding.UTF8.GetBytes(iv);

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] inData = Encoding.UTF8.GetBytes(sourceString);
                    try
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inData, 0, inData.Length);

                            cs.FlushFinalBlock();
                        }

                        return Convert.ToBase64String(ms.ToArray());
                    }
                    catch
                    {
                        return sourceString;
                    }
                }
            }
            catch { return sourceString; }
        }

        //解密
        /// <summary>
        /// DES解密函数
        /// </summary>
        /// <param name="encryptedString">解密字符</param>
        /// <param name="key">解密钥匙1</param>
        /// <param name="iv">解密钥匙2</param>
        /// <returns></returns>
        public string DesDecrypt(string encryptedString, string key, string iv)
        {
            byte[] btKey = Encoding.UTF8.GetBytes(key);

            byte[] btIV = Encoding.UTF8.GetBytes(iv);

            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    byte[] inData = Convert.FromBase64String(encryptedString);
                    try
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inData, 0, inData.Length);

                            cs.FlushFinalBlock();
                        }

                        return Encoding.UTF8.GetString(ms.ToArray());
                    }
                    catch
                    {
                        return encryptedString;
                    }
                }
            }
            catch
            {
                return encryptedString;
            }
        }

        //写INI（不加密）
        /// <summary>
        /// 把数据库相关信息写入ini文件中(不加密)
        /// </summary>
        /// <param name="serverContent">数据库地址</param>
        /// <param name="databaseContent">数据库名称</param>
        /// <param name="uidContent">数据库登录名</param>
        /// <param name="passwordContent">数据库登录密码</param>
        public void WriteContentToInt(string serverContent, string KeyName)
        {

            string strWriteContent = System.IO.Path.GetFileNameWithoutExtension(IntPath); 				//获取INI文件的文件名

            if (serverContent != "")
            {
                try
                {
                    WritePrivateProfileString(strWriteContent, KeyName, serverContent, IntPath);

                    Console.WriteLine("保存成功");
                }
                catch
                {
                    Console.WriteLine("保存失败");
                }
            }
        }

        //读INI字段值（不加密）
        public string GetIniKeyValue(string KeyName)
        {
            string KeyValue = string.Empty;
            try
            {
                string strReadContent = System.IO.Path.GetFileNameWithoutExtension(IntPath); 				//获取INI文件的文件名
                if (File.Exists(IntPath)) 											//判断是否存在该INI文件
                {
                    KeyValue = ContentReader(strReadContent, KeyName, "");				//读取INI文件中服务器节点的内容
                }
                else //如果文件不存在则创建ini文件
                {
                    KeyValue = "";
                }

                return KeyValue;
            }
            catch
            {
                KeyValue = "";
                return KeyValue;
            }
        }

        //读ini库信息（加密）
        /// <summary>
        /// 获取Ini文件中数据库的相关信息
        /// </summary>
        /// <returns>数据库连接的字符串</returns>
        public string GetConnetStr(int Ser)
        {

            string getIntStr = null;
            try
            {
                string SerName = "Servername1";
                string DBName = "Databasename1";
                string Uid = "Uid1";
                string Pwd = "Password1";

                switch (Ser)
                {
                    case 1:     //"设备管理库"
                        SerName = "Servername1";
                        DBName = "Databasename1";
                        Uid = "Uid1";
                        Pwd = "Password1";
                        break;
                    case 2:     //"授权库"
                        SerName = "Servername2";
                        DBName = "Databasename2";
                        Uid = "Uid2";
                        Pwd = "Password2";
                        break;
                    case 3:     //"录播库"
                        SerName = "Servername3";
                        DBName = "Databasename3";
                        Uid = "Uid3";
                        Pwd = "Password3";
                        break;
                }

                string strReadContent = System.IO.Path.GetFileNameWithoutExtension(IntPath); 				//获取INI文件的文件名
                if (File.Exists(IntPath)) 											//判断是否存在该INI文件
                {
                    ServerName = DesDecrypt(ContentReader(strReadContent, SerName, ""), Key1, Key2);				//读取INI文件中服务器节点的内容
                    DataBaseName = DesDecrypt(ContentReader(strReadContent, DBName, ""), Key1, Key2);				//读取INI文件中数据库节点的内容
                    UidName = DesDecrypt(ContentReader(strReadContent, Uid, ""), Key1, Key2);					//读取INI文件中用户节点的内容
                    PassWordName = DesDecrypt(ContentReader(strReadContent, Pwd, ""), Key1, Key2);						//读取INI文件中密码节点的内容
                    getIntStr = "Server=" + ServerName + ";database=" + DataBaseName + ";uid=" + UidName + ";pwd=" + PassWordName + ";Max Pool Size = 10;Enlist=true;Pooling=true;Connection Lifetime=100;Connection Timeout=30;";
                }
                else //如果文件不存在则创建ini文件
                {
                    getIntStr = "";
                }
                if ((ServerName == "") || (DataBaseName == "") || (UidName == "") || (PassWordName == ""))
                {
                    getIntStr = "";
                }
                return getIntStr;

                //---------------------------------

                //string strReadContent = System.IO.Path.GetFileNameWithoutExtension(IntPath); 				//获取INI文件的文件名
                //if (File.Exists(IntPath)) 											//判断是否存在该INI文件
                //{
                //    ServerName = DesDecrypt(ContentReader(strReadContent, "Servername", ""), Key1, Key2);				//读取INI文件中服务器节点的内容
                //    DataBaseName = DesDecrypt(ContentReader(strReadContent, "Databasename", ""), Key1, Key2);				//读取INI文件中数据库节点的内容
                //    UidName = DesDecrypt(ContentReader(strReadContent, "Uid", ""), Key1, Key2);					//读取INI文件中用户节点的内容
                //    PassWordName = DesDecrypt(ContentReader(strReadContent, "Password", ""), Key1, Key2);						//读取INI文件中密码节点的内容
                //    getIntStr = "Server=" + ServerName + ";database=" + DataBaseName + ";uid=" + UidName + ";pwd=" + PassWordName + "";
                //}
                //else //如果文件不存在则创建ini文件
                //{
                //    getIntStr = "";
                //}
                //if ((ServerName == "") || (DataBaseName == "") || (UidName == "") || (PassWordName == ""))
                //{
                //    getIntStr = "";
                //}
                //return getIntStr;
            }
            catch
            {
                getIntStr = "";
                return getIntStr;
            }

        }

        //数据库写INI（加密）
        /// <summary>
        /// 把数据库相关信息写入ini文件中
        /// </summary>
        /// <param name="serverContent">数据库地址</param>
        /// <param name="databaseContent">数据库名称</param>
        /// <param name="uidContent">数据库登录名</param>
        /// <param name="passwordContent">数据库登录密码</param>
        public void WriteContentToIntEnc(string serverContent, string databaseContent, string uidContent, string passwordContent, int serverNum)
        {
            string SerName = "Servername1";
            string DBName = "Databasename1";
            string Uid = "Uid1";
            string Pwd = "Password1";

            switch (serverNum)
            {
                case 1:     //"设备管理库"
                    SerName = "Servername1";
                    DBName = "Databasename1";
                    Uid = "Uid1";
                    Pwd = "Password1";
                    break;
                case 2:     //"授权库"
                    SerName = "Servername2";
                    DBName = "Databasename2";
                    Uid = "Uid2";
                    Pwd = "Password2";
                    break;
                case 3:     //"录播库"
                    SerName = "Servername3";
                    DBName = "Databasename3";
                    Uid = "Uid3";
                    Pwd = "Password3";
                    break;
                default: break;
            }

            string strWriteContent = System.IO.Path.GetFileNameWithoutExtension(IntPath); 				//获取INI文件的文件名

            if (serverContent != "" || databaseContent != "" || uidContent != "")
            {
                try
                {
                    WritePrivateProfileString(strWriteContent, SerName, EncryptDES(serverContent, Key1, Key2), IntPath); 		//修改INI文件中服务器节点的内容
                    WritePrivateProfileString(strWriteContent, DBName, EncryptDES(databaseContent, Key1, Key2), IntPath); 		//修改INI文件中数据库节点的内容
                    WritePrivateProfileString(strWriteContent, Uid, EncryptDES(uidContent, Key1, Key2), IntPath); 			//修改INI文件中用户节点的内容
                    WritePrivateProfileString(strWriteContent, Pwd, EncryptDES(passwordContent, Key1, Key2), IntPath); 			//修改INI文件中密码节点的内容           

                    Console.WriteLine("保存成功");
            //--------------------------------------

            //  string strPath = Application.StartupPath + "\\ConnectString.ini";
            //string strWriteContent = System.IO.Path.GetFileNameWithoutExtension(IntPath); 				//获取INI文件的文件名

            //if (serverContent != "" || databaseContent != "" || uidContent != "")
            //{
            //    try
            //    {
            //        if (File.Exists(IntPath))											//判断是否存在INI文件
            //        {
            //            WritePrivateProfileString(strWriteContent, "Servername", EncryptDES(serverContent, Key1, Key2), IntPath); 		//修改INI文件中服务器节点的内容
            //            WritePrivateProfileString(strWriteContent, "Databasename", EncryptDES(databaseContent, Key1, Key2), IntPath); 		//修改INI文件中数据库节点的内容
            //            WritePrivateProfileString(strWriteContent, "Uid", EncryptDES(uidContent, Key1, Key2), IntPath); 			//修改INI文件中用户节点的内容
            //            WritePrivateProfileString(strWriteContent, "Password", EncryptDES(passwordContent, Key1, Key2), IntPath); 			//修改INI文件中密码节点的内容            
            //        }
            //        else
            //        {
            //            WritePrivateProfileString(strWriteContent, "Servername", EncryptDES(serverContent, Key1, Key2), IntPath); 		//修改INI文件中服务器节点的内容
            //            WritePrivateProfileString(strWriteContent, "Databasename", EncryptDES(databaseContent, Key1, Key2), IntPath); 		//修改INI文件中数据库节点的内容
            //            WritePrivateProfileString(strWriteContent, "Uid", EncryptDES(uidContent, Key1, Key2), IntPath); 			//修改INI文件中用户节点的内容
            //            WritePrivateProfileString(strWriteContent, "Password", EncryptDES(passwordContent, Key1, Key2), IntPath); 			//修改INI文件中密码节点的内容
            //        }
            //        Console.WriteLine("保存成功");
                }
                catch
                {
                    Console.WriteLine("保存失败");
                }
            }


        }

        //读服务器IP（加密）
        /// <summary>
        /// 获取服务器IP地址
        /// </summary>
        /// <returns></returns>
        public string GetServerIP(int Ser)
        {
            string SerName = "Servername1";

            switch (Ser)
            {
                case 1:     //"设备管理库"
                    SerName = "Servername1";
                    break;
                case 2:     //"授权库"
                    SerName = "Servername2";
                    break;
                case 3:     //"录播库"
                    SerName = "Servername3";
                    break;
            }

            try
            {
                string strReadContent = System.IO.Path.GetFileNameWithoutExtension(IntPath); 				//获取INI文件的文件名
                if (File.Exists(IntPath)) 											//判断是否存在该INI文件
                {
                    //ServerName = DesDecrypt(ContentReader(strReadContent, "Servername", ""), Key1, Key2);				//读取INI文件中服务器节点的内容
                    ServerName = DesDecrypt(ContentReader(strReadContent, SerName, ""), Key1, Key2);				//读取INI文件中服务器节点的内容
                }

                return ServerName;
            }
            catch
            {
                ServerName = "";
                return ServerName;
            }
        }

        //
        public string GetConnetStrByKey(int Ser) 
        {
            string getIntStr = null;
            try
            {
                string SerName = "Servername1";
                string DBName = "Databasename1";
                string Uid = "Uid1";
                string Pwd = "Password1";

                switch (Ser)
                {
                    case 1:     //"设备管理库"
                        SerName = "Servername1";
                        DBName = "Databasename1";
                        Uid = "Uid1";
                        Pwd = "Password1";
                        break;
                    case 2:     //"授权库"
                        SerName = "Servername2";
                        DBName = "Databasename2";
                        Uid = "Uid2";
                        Pwd = "Password2";
                        break;
                    case 3:     //"录播库"
                        SerName = "Servername3";
                        DBName = "Databasename3";
                        Uid = "Uid3";
                        Pwd = "Password3";
                        break;
                }

                string strReadContent = System.IO.Path.GetFileNameWithoutExtension(IntPath); 				//获取INI文件的文件名
                if (File.Exists(IntPath)) 											//判断是否存在该INI文件
                {
                    //ServerName = DesDecrypt(ContentReader(strReadContent, SerName, ""), Key1, Key2);				//读取INI文件中服务器节点的内容
                    //DataBaseName = DesDecrypt(ContentReader(strReadContent, DBName, ""), Key1, Key2);				//读取INI文件中数据库节点的内容
                    //UidName = DesDecrypt(ContentReader(strReadContent, Uid, ""), Key1, Key2);					//读取INI文件中用户节点的内容
                    //PassWordName = DesDecrypt(ContentReader(strReadContent, Pwd, ""), Key1, Key2);						//读取INI文件中密码节点的内容

                    ServerName = ContentReader(strReadContent, SerName, "");				//读取INI文件中服务器节点的内容
                    DataBaseName = ContentReader(strReadContent, DBName, "");				//读取INI文件中数据库节点的内容
                    UidName = ContentReader(strReadContent, Uid, "");					//读取INI文件中用户节点的内容
                    PassWordName = ContentReader(strReadContent, Pwd, "");						//读取INI文件中密码节点的内容

                    getIntStr = "Server=" + ServerName + ";database=" + DataBaseName + ";uid=" + UidName + ";pwd=" + PassWordName + ";Max Pool Size = 10;Enlist=true;Pooling=true;Connection Lifetime=100;Connection Timeout=30;";
                }
                else //如果文件不存在则创建ini文件
                {
                    getIntStr = "";
                }
                if ((ServerName == "") || (DataBaseName == "") || (UidName == "") || (PassWordName == ""))
                {
                    getIntStr = "";
                }
                return getIntStr;

                //---------------------------------
            }
            catch
            {
                getIntStr = "";
                return getIntStr;
            }
        }
    }
}
